package com.ruoyi.order.service;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiFileUploadSingleRequest;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest.FormComponentValueVo;
import com.dingtalk.api.response.OapiFileUploadSingleResponse;
import com.dingtalk.api.response.OapiProcessinstanceCreateResponse;
import com.ruoyi.order.Dto.ApprovalForm;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;

import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class DingTalkApprovalService {

    private String appKey = "dingi1egsdxwi6g6yhgy";

    private String appSecret = "Ev73Ex8dpQVbDQHe6BQVZ_YaFpwcZV1fomx7127tq3vONDgUMPf6pJ8_t8B9Nn5A";


    private Long agentId = 3928939802L;

    private String processCode = "PROC-BDE35989-AC4D-467D-9BBB-989C5A431455"; // 审批模板的processCode

    /**
     * 获取访问令牌
     */
    public String getAccessToken() throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client authClient =
                new com.aliyun.dingtalkoauth2_1_0.Client(
                        new com.aliyun.teaopenapi.models.Config()
                                .setProtocol("https")
                                .setRegionId("central")
                );

        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest tokenRequest =
                new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                        .setAppKey(appKey)
                        .setAppSecret(appSecret);

        return authClient.getAccessToken(tokenRequest).getBody().getAccessToken();
    }

    /**
     * 发起审批实例（使用旧版SDK）
     *
     * @param form 审批表单数据
     * @param originatorUserId 发起人钉钉用户ID
     * @return 审批实例ID
     */
    public String createApprovalInstance(ApprovalForm form, String originatorUserId, Long deptId)
            throws Exception {

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
        OapiProcessinstanceCreateRequest request = new OapiProcessinstanceCreateRequest();

        // 设置审批基本信息
        request.setAgentId(agentId);
        request.setProcessCode(processCode);
        request.setOriginatorUserId(originatorUserId);
        request.setDeptId(deptId);
        OapiProcessinstanceCreateRequest.FormComponentValueVo attachment =
                new OapiProcessinstanceCreateRequest.FormComponentValueVo();

        attachment.setName("附件"); // 表单控件名称
        attachment.setValue(form.getAttachmentList());
        request.setFormComponentValues(Collections.singletonList(attachment));


        try {
            OapiProcessinstanceCreateResponse response = client.execute(request, getAccessToken());
            if (response.isSuccess()) {
                return response.getProcessInstanceId();
            } else {
                throw new RuntimeException("创建审批失败: " + response.getErrmsg());
            }
        } catch (ApiException e) {
            throw new RuntimeException("调用钉钉接口失败: " + e.getMessage(), e);
        }
    }

    /**
     * 添加表单值
     */
    private void addFormValue(List<FormComponentValueVo> formValues, String name, String value) {
        if (value != null && !value.isEmpty()) {
            FormComponentValueVo vo = new FormComponentValueVo();
            vo.setName(name);
            vo.setValue(value);
            formValues.add(vo);
        }
    }

    /**
     * 上传钉钉上传媒体文件接口
     * @param accessToken
     * @param filePath
     * @return
     * @throws Exception
     */
    public String uploadFile(String accessToken, String filePath) throws Exception {
        OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
        request.setAgentId("3928939802");
        request.setFileSize(1000L);
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?"+ WebUtils.buildQuery(request.getTextParams(),"utf-8"));
        request = new OapiFileUploadSingleRequest();
        request.setFile(new FileItem(filePath));
        OapiFileUploadSingleResponse response = client.execute(request,accessToken);
        String mediaId = response.getMediaId();
        System.out.println("MediaId:"+mediaId);
        return mediaId;
    }


}